import storage from 'store'
import expirePlugin from 'store/plugins/expire'
import { login, getInfo, logout } from '@/api/login'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { welcome } from '@/utils/util'
import { defineStore } from 'pinia'
storage.addPlugin(expirePlugin)
const useUserStore = defineStore('user', {
  state: () => ({
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {}
  }),
  getters: {
    get_token: state => state.token,
    get_avatar: state => state.avatar,
    get_name: state => state.name,
    get_welcome: state => state.welcome,
    get_roles: state => state.roles,
    get_info: state => state.info
  },
  actions: {
    SET_TOKEN(token) {
      this.token = token
    },
    SET_NAME({ name, welcome }) {
      this.name = name
      this.welcome = welcome
    },
    SET_AVATAR(avatar) {
      this.avatar = avatar
    },
    SET_ROLES(roles) {
      this.roles = roles
    },
    SET_INFO(info) {
      this.info = info
    },
    // 登录
    Login(userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          const result = response.result
          storage.set(ACCESS_TOKEN, result.token, new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
          this.SET_TOKEN(result.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetInfo() {
      return new Promise((resolve, reject) => {
        // 请求后端获取用户信息 /api/user/info
        getInfo().then(response => {
          const { result } = response
          if (result.role && result.role.permissions.length > 0) {
            const role = { ...result.role }
            role.permissions = result.role.permissions.map(permission => {
              const per = {
                ...permission,
                actionList: (permission.actionEntitySet || {}).map(item => item.action)
              }
              return per
            })
            role.permissionList = role.permissions.map(permission => { return permission.permissionId })
            // 覆盖响应体的 role, 供下游使用
            result.role = role

            this.SET_ROLES(role)
            this.SET_INFO(result)
            this.SET_NAME({ name: result.name, welcome: welcome() })
            this.SET_AVATAR(result.avatar)
            // 下游
            resolve(result)
          } else {
            reject(new Error('getInfo: roles must be a non-null array !'))
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    Logout() {
      return new Promise((resolve) => {
        logout().then(() => {
          this.SET_TOKEN('');
          this.SET_ROLES([]);
          storage.remove(ACCESS_TOKEN)
          resolve()
        }).catch((err) => {
          console.log('logout fail:', err)
          // resolve()
        }).finally(() => {
        })
      })
    }
  }
})
export default useUserStore
